# routers/products.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from db import Product
from pydantic import BaseModel
from typing import Optional

router = APIRouter(prefix="/products", tags=["products"])

# Pydantic 模型定义
class ProductCreate(BaseModel):
    name: str
    market: str
    category: str
    img_url: Optional[str] = None
    price: float
    description: Optional[str] = None
    hot_index: Optional[int] = None

class ProductResponse(ProductCreate):
    id: int
    
    class Config:
        orm_mode = True

# 依赖项
def get_db():
    from db import SessionLocal
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
        
@router.post("/batch/", response_model=List[ProductResponse])
def create_products(products: List[ProductCreate], db: Session = Depends(get_db)):
    """
    批量创建商品
    
    - products: 商品列表
    - 返回创建的商品列表
    """
    db_products = []
    for product_data in products:
        db_product = Product(**product_data.dict())
        db_products.append(db_product)
    
    db.add_all(db_products)
    db.commit()
    
    # 刷新所有对象以获取它们的ID
    for db_product in db_products:
        db.refresh(db_product)
        
    return db_products

# Product 相关 API
@router.post("/", response_model=ProductResponse)
def create_product(product: ProductCreate, db: Session = Depends(get_db)):
    db_product = Product(**product.dict())
    db.add(db_product)
    db.commit()
    db.refresh(db_product)
    return db_product

@router.get("/", response_model=List[ProductResponse])
def read_products(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    products = db.query(Product).offset(skip).limit(limit).all()
    return products

@router.get("/{product_id}", response_model=ProductResponse)
def read_product(product_id: int, db: Session = Depends(get_db)):
    db_product = db.query(Product).filter(Product.id == product_id).first()
    if db_product is None:
        raise HTTPException(status_code=404, detail="Product not found")
    return db_product

@router.put("/{product_id}", response_model=ProductResponse)
def update_product(product_id: int, product: ProductCreate, db: Session = Depends(get_db)):
    db_product = db.query(Product).filter(Product.id == product_id).first()
    if db_product is None:
        raise HTTPException(status_code=404, detail="Product not found")
    
    for key, value in product.dict().items():
        setattr(db_product, key, value)
        
    db.commit()
    db.refresh(db_product)
    return db_product

@router.delete("/{product_id}", response_model=ProductResponse)
def delete_product(product_id: int, db: Session = Depends(get_db)):
    db_product = db.query(Product).filter(Product.id == product_id).first()
    if db_product is None:
        raise HTTPException(status_code=404, detail="Product not found")
    
    db.delete(db_product)
    db.commit()
    return db_product